package com.chang.multithread.Safe;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class wait {
    static final Object lock=new Object();
    public static void main(String[] args) {
        new Thread(()->{
            synchronized (lock){
            log.debug("t1执行！");
                try {
                    lock.wait();
                    //lock.wait(1000);//等待1秒，如果没有没有被唤醒，则继续往下继续执行代码
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("t1竞争成功被唤醒");
            }
        },"t1").start();

        new Thread(()->{
            synchronized (lock){
            log.debug("t2执行！");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("t2竞争成功被唤醒");
            }
        },"t2").start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.debug("主线程准备唤醒一个线程！");
        synchronized (lock){
            lock.notify();//随机唤醒一个等待的线程（已获得锁的线程中调用wait的方法）
            lock.notifyAll();   //唤醒所有等待的线程
        }
        log.debug("看看那个线程竞争成功被唤醒！");
    }
}
